﻿/**
 * 页面逻辑部分
 */
// 有领队
// var memberId    =   '6C3C37BC34863C8DE055000000000001'
// var mobile      =   '15281265497'

// 没有领队
var memberId    =   '6C3C37BC34853C8DE055000000000001'
var memberMobile      =   '15376368542'

// var memberId            =   getCookie('memberId')
// var memberMobile        =   getCookie('memberMobile')
var memberName          =   getCookie('memberName')
var memberTeamId        =   getCookie('memberTeamId')
var memberTeamUserType  =   getCookie('memberTeamUserType')
var memberOpenId        =   getCookie('memberOpenId')	//用戶表綁定的openId
var memberHead          =   getCookie('memberHead')
var wxOpenId	        =   getCookie('wxOpenId')	//微信打开首页后，当前微信账号的openId
var wxHead              =   getCookie('wxHead')
console.log(memberId)
console.log(memberMobile)
// 已登录效果
if( memberId && memberMobile ) {
    $("#person-li").css('display','block')
    $("#login-li,#reg-li,#go-reg").css('display','none')

    $("#person-li").hover(
        function () {
            $(this).addClass("active");
        },
        function () {
            $(this).removeClass("active");
        }
    );
}
// 拦截a标签的href
var links = document.querySelectorAll('a')
Array.prototype.forEach.call(links, function (link) {
    link.addEventListener('click', function (evt) {
        evt.preventDefault()
        if( $(this).attr('href') ) getPageRoute($(this).attr('href'))
    })
})

// 获取短信验证码 定时器
function countdown(element) {
    var s;
    var timer = 60;
    s = setInterval( function () {
        if(timer > 0){
            timer--;
            element.text('（ '+ timer +' ）').attr('disabled', true).css('background', '#DDDDDD');
        }else {
            clearInterval(s);
            element.text('重新发送').attr('disabled', false).css('background', '#F4ACBE');
            timer = 60;
            return
        }
    }, 1000)
}
// 获取URL中的参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}
//获取cookies
function getCookie(cookieName) {
    var strCookie = decodeURI(document.cookie);
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (cookieName == arr[0]) {
            return arr[1];
        }
    }
    return "";
}
//页面路由
function getPageRoute(url) {
    //【 部署到后台时  取消下一行注释 】
    // url = url.replace(/\.html/,'')
    window.location.href = routerDomain + url;
}

// 报名注册界面
var Reg = {
    init: function () {
        // 新增队伍
        $('.add-team-btn').on('click', function () {
            $('.add-team-dialog').fadeIn()
        })
        // 关闭弹窗
        $('.dialog').find('.dialog-close').on('click', function () {
            $('.dialog').fadeOut();
        })
        $('#keyword').on('click', function () {
            $('.select-list').fadeToggle();
        })
        this.getVerifyCodeWhenReg();
        this.getUserInfoByMobile();
        this.getHospitalList();
        this.addNewHospital();
        this.getPositionList();
        this.selectBU();
        this.addNewTeam();
        this.doReg()
    },
    // 获取短信验证码
    getVerifyCodeWhenReg: function () {
        // 获取短信验证码
        $('#registerSend').on('click', function () {
            var param = {};
            param.mobile = $('#mobile').val();
            // 空判断
            if ( !param.mobile )  return weui.toast('手机号不能为空');
            Api.getVerifyCodeWhenReg( param, function (res) {
                if( res.code !== 0 ) return weui.toast(res.msg);
                countdown( $("#registerSend") )
            } )
        });
    },
    // 根据手机号  拉取相关信息
    getUserInfoByMobile: function () {
        var that = this
        $("#mobile").on('input propertychange', function () {
            var params = {};
            params.mobile = $('#mobile').val();
            if( params.mobile.length == 11 ) Api.getUserInfoByMobile(params,function (res) {
                if(!res.data) return ;
                // 赋值
                if( res.data.name )             $("#userName").val(res.data.name)
                if( res.data.hospitalName )     $("#keyword").val(res.data.hospitalName) & that.getTeamList(res.data.hospitalId) & $("#keyword").data('hospital-id',res.data.hospitalId)
                if( res.data.position )         $("#position").val(res.data.position)
                if( res.data.bu )               $("#BU").val(res.data.bu)
            })
        })
        // 填充信息
    },
    // 获取医院列表
    getHospitalList: function () {
        var that = this;
        //  根据关键字获取列表
        $("#keyword").on('input propertychange',function () {
            var params = {}
            params.keyWords = $("#keyword").val()
            console.warn(params)
            // 三个字后才触发
            if( params.keyWords.length>=3 ) Api.getHospitalList(params, function (res) {
                if( !res.data || !res.data.length ) return ;
                $("#hospitalList ~ p").remove()
                $("#hospitalList").after($.templates("#hospitalList").render(res.data));
                // 选择后  触发队伍 和 赛区
                $("#hospitalList ~ p").on('click', function () {
                    $('.select-list').fadeOut();
                    $("#keyword").val($(this).text()).css('color', '#666161')
                    $("#keyword").data('',$(this).text())
                    // 获取可选队伍
                    that.getTeamList($(this).data('hospital-id'))
                    $("#keyword").data('hospital-id',$(this).data('hospital-id'))
                    // 赛区
                    $("#matchArea").val($(this).data('match-area')||'')
                })
            })
        })
    },
    // 获取队伍列表
    getTeamList: function (hospitalId) {
        var that = this;
        var params = {}
        params.hospitalId = hospitalId;
        Api.getTeamListById(params,function (res) {
            $("#matchArea").val(res.data.matchArea)
            res.data.listTeam.forEach(function (item) {
                item.label = item.hospitalName
                item.value = item.hospitalId
            })
            $("#teamName").on('click', function () {
                weui.picker(res.data.listTeam, {
                    onConfirm: function (result) {
                        $("#teamName").val(result[0].label)
                        $("#teamName").data('team-id',result[0].value)
                        // 选择后  更新可选身份
                        $("#userType").val('')
                        $("#userType").data('user-type','')
                        that.getRoleList();
                    }
                })
            })
        })
    },
    // 获取职称列表
    getPositionList:  function () {
        var that = this;
        var params = {}
        Api.getPositionList(params,function (res) {
            if( !res.data || !res.data.length ) return ;
            res.data.forEach(function (item) {
                item.label = item.value
                item.value = item.value
            })
            $("#position").on('click', function () {
                weui.picker(res.data, {
                    onConfirm: function (result) {
                        console.log(result[0].value)
                        $("#position").val(result[0].value)
                        // 选择后  更新可选身份
                        $("#userType").val('')
                        $("#userType").data('user-type','')
                        that.getRoleList();
                    }
                })
            })
        })
    },
    // 获取参赛身份
    getRoleList: function () {
        var params = {}
        params.position = $("#position").val()
        if( $("#teamName").data('team-id') ) params.teamId = $("#teamName").data('team-id');
        Api.getRoleList(params, function (res) {
            if( !res.data || !res.data.length ) return ;
            res.data.forEach(function (item) {
                item.label = item.roleName
                item.value = item.userType
            })
            $("#userType").on('click', function () {
                weui.picker(res.data, {
                    onConfirm: function (result) {
                        $("#userType").val(result[0].label)
                        $("#userType").data('user-type',result[0].value)
                    }
                })
            })
        })
    },
    // 选中BU
    selectBU: function () {
        $("#BU").on('click',function () {
            weui.picker([
                {label:'CABU', value:'CABU'},
                {label:'CDBU', value:'CDBU'},
                {label:'CXBU', value:'CXBU'},
                ], {
                onConfirm: function (result) {
                    $("#BU").val(result[0].label)
                }
            })
            $("#BU").val($(this).text()).css('color', '#666161')
        })
    },
    // 新增医院
    addNewHospital: function () {
        var that = this
        // 新增医院
        $('.add-hospital-btn').on('click', function () {
            $('.add-hospital-dialog').fadeIn(1000,function () {
                new PCAS("province","city")
                $("#addNewHospital").on('click', function () {
                    var params = {}
                    params.province     = $("#province").val()
                    params.city         = $("#city").val()
                    params.hospitalName = $("#hospitalNameAdd").val()
                    if( !params.province || !params.city || !params.hospitalName )  return weui.toast('请确认医院信息');
                    Api.addNewHospital(params,function (res) {
                        if( res.code !== 0 ) return weui.toast(res.msg);
                        $("#keyword").val(res.data.hospital.hospitalName)
                        $("#keyword").data('hospital-id',res.data.hospital.hospitalId)
                        $('.dialog').fadeOut();
                        that.getTeamList(res.data.hospital.hospitalId);
                    })
                })
            })
        })

    },
    // 新增队伍
    addNewTeam: function () {
        $("#addTeam").on('click', function () {
            $("#teamName").val( $("#teamNameAdd").val() )
            $('.dialog').fadeOut();
        })
    },
    // 报名操作
    doReg: function () {
        $("#do-reg").on('click', function () {
            var params = {}
            params.mobile = $("#mobile").val();
            params.password = $("#password").val()
            params.name = $("#userName").val()
            params.position = $("#position").val()
            params.matchArea = $("#matchArea").val()
            params.teamName = $("#teamName").val()
            params.teamId = $("#teamName").data('team-id')
            params.userType = $("#userType").data('user-type')
            params.BU = $("#BU").val()
            params.hospitalId = $("#keyword").data('hospital-id')
            params.verifyCode = $("#verificationCode").val()
            params.source = '1'
            console.warn(params)
            if (!params.mobile || !params.password || !params.name || !params.position
                || !params.matchArea || !params.teamName || !params.teamId || !params.userType
                || !params.BU || !params.hospitalId || !params.verifyCode) return weui.toast('参数不完整');
            Api.doReg(params, function (res) {
                if( res.code !== 0 ) return weui.toast(res.msg);
                getPageRoute('index.html')
            })
        })
    }
}

// 登录界面
var Login = {
    init: function () {

        $('.tab-head-box').find('.tab-head-item').on('click', function () {
            $(this).addClass('active').siblings().removeClass('active');
            var id = $(this).index();
            $('.tab-content').find('.tab-item').eq(id).addClass('active').siblings().removeClass('active');
        })
        this.getVerifyCodeWhenLogin()
        this.loginByPasswordWechat()
        this.loginByVerifyCodeWechat();
    },
    // 获取短信验证码
    getVerifyCodeWhenLogin: function () {// 获取短信验证码
        $('#loginSend').on('click', function () {
            var param = {};
            param.mobile = $('#accountNumber1').val();
            // 空判断
            if ( !param.mobile )  return weui.toast('请输入手机号');
            Api.getVerifyCodeWhenLogin( param, function (res) {
                if( res.code !== 0 ) return weui.toast(res.msg)
                countdown( $("#loginSend") )
            } )
        });

    },
    // 根据账号密码登录
    loginByPasswordWechat: function () {
        $("#loginByPassword").on('click', function () {
            var params = {}
            params.mobile       = $("#accountNumber").val();
            params.password     = $("#loginPassword").val();
            if( !params.mobile || !params.password ) return weui.toast('参数不完整');
            Api.loginByPasswordWechat(params, function (res) {
                if( !res.code !== 0 ) return weui.toast(res.msg)
                getPageRoute('index.html')
            })
        })
    },
    // 根据验证码登录
    loginByVerifyCodeWechat:function () {
        $("#loginByVerifyCode").on('click', function () {
            var params = {}
            params.mobile       = $("#accountNumber1").val();
            params.verifyCode     = $("#verificationCode").val();
            if( !params.mobile || !params.verifyCode ) return weui.toast('参数完整')
            Api.loginByVerifyCodeWechat(params, function (res) {
                if( !res.code !== 0 ) return layer.open({
                    content: res.msg
                    ,skin: 'msg'
                    ,time: 2 //2秒后自动关闭
                });
                getPageRoute('index.html')
            })
        })

    }
}

// 找回密码界面
var Retrieve = {
    init: function () {
        this.getVerifyCodeWhenRetrieve()
        this.doRetrieve()
    },
    // 获取短信验证码
    getVerifyCodeWhenRetrieve: function () {
        $('#retrieveSend').on('click', function () {
            var param = {};
            param.mobile = $('#accountNumber').val();
            // 空判断
            if ( !param.mobile )  return weui.toast('手机号不能为空');
            Api.getVerifyCodeWhenRetrieve( param, function (res) {
                if( res.code !== 0 ) return weui.toast('res.msg');
                countdown( $("#retrieveSend") )
            } )
        });
    },
    // 进行修改密码操作
    doRetrieve: function () {
        $("#doRetrieve").on('click', function () {
            var params = {}
            params.mobile       = $("#accountNumber").val();
            params.verifyCode   = $("#verificationCode").val();
            params.newPassword  = $("#loginPassword").val();
            if( !params.mobile || !params.verifyCode || !params.newPassword ) return weui.toast('参数不完整')
            Api.doRetrieve(params, function (res) {
                if( res.code !== 0 ) return weui.toast(res.msg);
                getPageRoute('login.html');
            })
        })
    }
}

// 个人中心界面
var My = {
    data:{
        userInfo:undefined,
        teamList: undefined
    },
    init: function () {

        $('.tab-navbar').find('.item').on('click', function () {
            $(this).addClass('active').parents('.tab-navbar_item').siblings().find('.item').removeClass('active');
            var id = $(this).parents('.tab-navbar_item').index();
            $('.tab-panel').find('.tab-panel_item').eq(id).addClass('active').siblings().removeClass('active');
        })
        $('.edit-btn').on('click', function () {
            $('.information-editing').fadeIn();
        });
        $('.dialog-close').on('click', function () {
            $('.dialog').fadeOut();
        })
        $('.invite-btn').on('click', function () {
            $('.rich-scan').fadeIn();
        })
        this.getPersonalInfo();
        this.getTeamInfoByMobile()
    },
    // 获取个人信息
    getPersonalInfo: function () {
        var that = this
        var params = {}
        params.memberId =   memberId
        params.mobile   =   memberMobile;
        Api.getPersonalInfo(params,function (res) {
            that.data.userInfo = res.data;
            if( res.code !== 0 ) return weui.toast(res.msg);
            // 头像
            $("#head").attr('src',res.data.head)
            // 昵称
            $("#nick").text(res.data.name)
            // 手机
            if( res.data.mobile )   $("#mobile").text(res.data.mobile)
            // 医院
            if( res.data.hospitalName ) $("#hospital").text(res.data.hospitalName)
            // 职称
            if( res.data.position ) $("#job_name").text(res.data.position)
            // 澳美中国儿科研究工艺基金
            if( res.data.score )    $("#num").text(res.data.score)
            // 参赛身份
            if( res.data.userTypeName ) $("#role").text(res.data.userTypeName)
        })
    },
    // 获取队伍信息
    getTeamInfoByMobile: function () {
        var that = this
        var params = {}
        params.mobile = memberMobile;
        Api.getTeamInfoByMobile(params, function (res) {
            if( !res.data || !res.data.length) return false;
            that.data.teamList = res.data;

            // 显示队伍列表
            $("#myTeamList ~ li").remove()
            $("#myTeamList").after($.templates("#myTeamList").render(res.data));
            // 默认显示第一个
            $(".my-team-list  li:first").addClass('active')
            that.showTeamInfo(0)

            // 点击事件
            $(".my-team-list  li").on('click', function () {
                $(".my-team-list  li").removeClass('active')
                $(this).addClass('active')
                that.showTeamInfo($(this).index())
            })
        })
    },
    // 显示当前队伍信息
    showTeamInfo: function (index) {
        var teamInfo = this.data.teamList[index]
        // 队伍名
        $("#team-name").text(teamInfo.teamName)
        // 挑战分数  数组  第一轮 第二轮
        $("#score").text(teamInfo.examScore.join(','))
        // 导师信息
        var leaderInfo =  teamInfo.teamMember.filter(function (item) {
            return item.userType == 1;
        })[0]
        if( leaderInfo ) {
            $("#leader").text(leaderInfo.name)
            $(".btn-box").css('display','none')
        }else{
            this.addTutorInfo();
        }
        // 队伍成员
        if( teamInfo.teamMember ) $("#team").text(teamInfo.teamMember.map(function (item) {
            return item.name;
        }).join(','))

    },
    // 编辑导师信息
    addTutorInfo: function () {
        var that = this
        // 弹窗效果
        $('.send-btn').on('click', function () {
            $('.add-hospital-dialog').fadeIn()
        })
        $(".close").on('click',function () {
            $('.add-hospital-dialog').fadeOut()
        })
        // 根据手机号获取导师信息
        $("#leaderMobile").on('input propertychange', function () {
            var params = {};
            params.mobile       = $('#leaderMobile').val();
            params.hospitalId   = that.data.userInfo.hospitalId
            if( params.mobile.length == 11 ) Api.getTutorInfoByMobile(params,function (res) {
                if( res.data.membInfo  )   $("#leaderName").val(res.data.membInfo.name)
            })
        })
        $("#doAddLeaderInfo").on('click', function () {
            var params = {};
            params.mobile   = $('#leaderMobile').val();
            params.name     = $("#leaderName").val()
            params.teamId   = that.userInfo.teamId
            Api.addTutorInfo(params, function (res) {
                if( res.code !== 0 ) return weui.toast(res.msg);
                history.go(0)
            })
        })
    }
}

// 首页
var Home = {
    init: function () {
        $('.tab-strip').on('click', 'li', function () {
            $(this).addClass('active').siblings().removeClass('active');
        })
    },
    // 根据是否登录 判断显示报名 答题按钮
}

// 赛事排名界面
var Ranking = {
    init: function () {
        this.getAreaList()
    },
    // 获取赛区列表
    getAreaList: function () {
        var that = this
        var params = {}
        Api.getAreaList(params, function (res) {
            if( !res.data || !res.data.length ) return ;
            $("#areaList ~ p").remove()
            $("#areaList").after($.templates("#areaList").render(res.data));
            // 默认第一个
            that.getTeamRankingByArea(res.data[0].value)
            $("#areaList ~ li").on('click', function () {
                that.getTeamRankingByArea($(this).text())
            })
        })
    },
    // 获取赛区队伍列表
    getTeamRankingByArea: function (matchArea) {
        var params = {}
        params.matchArea = matchArea.trim()
        console.log(params)
        Api.getTeamRankingByArea(params, function (res) {
            if( !res.data || !res.data.length ) return ;
            console.log(res)
        })
    }
}

// 赛事要闻列表界面
var News = {
    init: function () {
        this.getNewsList()
    },
    // 获取资讯列表
    getNewsList: function () {
        var params = {}
        Api.getNewsList(params, function (res) {
            if( !res.data || !res.data.length ) return ;
            $("#newsList ~ p").remove()
            $("#newsList").after($.templates("#newsList").render(res.data));
        })
    }
}

// 赛事要闻详情界面
var NewsDetail = {
    init: function () {
        var newsId = getUrlParam('newsId');
        this.getNewsDetail(newsId)
    },
    // 获取资讯详情 【是否需要返回资讯列表】
    getNewsDetail: function (newsId) {
        var params = {}
        params.newsId = newsId;
        Api.getNewsDetail(params, function (res) {
            console.warn(res)
            if( res.data.title )        $("#news-title").html(res.data.title)
            if( res.data.formatTime )   $("#news-pubdate").html(res.data.formatTime)
            if( res.data.content )      $("#news-content").html(res.data.content)
        })
    }
}

var Exam = {
    init: function () {
    }
}

// 去答题界面
var EXAM_API = {
    examInit: function () {
        EXAM_API.getPlayExam();
        EXAM_API.keepUpExamReset();
        EXAM_API.updateAuto();
    },
    //获取题目列表
    getPlayExam: function () {
        //获取当前赛事阶段id
        var subMatchId = PKTZ_API.getCookie('subMatchId');
        var memberId = PKTZ_API.getCookie('memberId');
        var id = {
            subMatchId: subMatchId,
            memberId: memberId,
            source: 1
        };
        PKTZ_API.getPlayExam(id);
    },
    //中途退出，再次答题，初始化答案
    keepUpExamReset: function () {
        //中途退出，再次答题，初始化答案
        $('.exam-content').find('.options').each(function (i) {
            var answer = $(this).data('key');
            var model = '<li><div>'+ (i+1) +'</div></li>';
            if(answer != 0){
                var len = answer.length;
                var _answer = answer.split('');
                for(var t = 0; t < len; t++){
                    $(this).find('li input').each(function () {
                        var value = $(this).val();
                        if(value == _answer[t]){
                            $(this).prop('checked', true);
                        }
                    })
                }
                model = '<li class="finished"><div>'+ (i+1) +'</div></li>';
            }
            //初始化答题记录卡
            $('.marker-list').append(model);
        });
    },
    //提交试题
    submitExam: function (callback) {
        var list = EXAM_API.getAnserList();
        var answerTime = $('.exam-content').data('answerTime');
        var remainingTime = $('.exam-content').data('remainingTime');
        var times = count > remainingTime ? remainingTime : count;
        var param = {
            id: $('.exam-content').data('examId'),
            questionId: $('.exam-content').data('questionId'),
            answerTime: times + answerTime,
            submitQuestionAnswer: list,
            source: 1
        };
        PKTZ_API.submitExam(param,callback);
    },
    //更新试题
    updateExam: function () {
        var list = EXAM_API.getAnserList();
        var answerTime = $('.exam-content').data('answerTime');
        var remainingTime = $('.exam-content').data('remainingTime');
        var times = count > remainingTime ? remainingTime : count;
        var param = {
            id: $('.exam-content').data('examId'),
            answerTime: times + answerTime,
            submitQuestionAnswer: list
        };
        PKTZ_API.updateExam(param);
    },
    //每过5秒自动更新试题
    updateAuto: function () {
        var s;
        var number = 0;
        s = setInterval(function () {
            number++;
            var remainingTime = $('.exam-content').data('remainingTime');
            if(number%5 == 0 && remainingTime){
                EXAM_API.updateExam();
            }
            if(number == remainingTime) clearInterval(s);
        }, 1000);
    },
    //获取当前已答试题结果，用以最终提交
    getAnserList: function () {
        var list = [];
        $('.exam-content').find('.options').each(function () {
            var value = $(this).data('key');
            if(value){
                list.push(value);
            }else {
                value = 0;
                list.push(value);
            }
        });
        var _list = list.join('|');
        return _list;
    }
};